package com.jie.client.service.ui.view;

import com.jie.client.core.ClientApplication;
import com.jie.client.core.handler.ClientWriteHandler;
import com.jie.client.service.entity.model.Group;
import com.jie.client.service.ui.constant.ViewMapConstant;
import com.jie.client.service.ui.model.SetNode;
import com.jie.client.service.ui.view.cell.GroupListCell;
import com.jie.client.service.ui.view.item.GroupItem;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @author XieZhiJie
 * @date 2022/04/28 21:25
 */
public class GroupListView {

    private final Logger logger = LoggerFactory.getLogger(GroupListView.class);

    private final Stage stage = new Stage();

    /**
     * 群聊列表视图
     */
    public final ListView<GroupItem> groupItemListView = new ListView<>();

    /**
     * 存放已经打开了的群聊列表id
     */
    private final Set<Integer> groupChatSet = ((SetNode) ClientApplication.VIEW_MAP.get(ViewMapConstant.GROUP_CHAT_SET)).set;

    /**
     * 创建群聊列表
     */
    public void createGroupListView() {
        ClientApplication.VIEW_MAP.put(ViewMapConstant.GROUP_LIST_VIEW, this);
        // 放群聊列表和功能Box的Box
        VBox groupListBox = new VBox();

        // 设置群聊列表
        // 不可编辑
        this.groupItemListView.setEditable(false);

        // 设置列表怎么展示
        this.groupItemListView.setCellFactory(param -> new GroupListCell());

        // 设置双击就弹出聊天框
        this.groupItemListView.setOnMouseClicked(this::onOpenGroupAction);

        // 建群 和 退群 的按钮
        Button createGroupButton = new Button("创建群聊");
        Button joinGroupButton = new Button("加入群聊");
        Button quitGroupButton = new Button("退群");

        // 设置 建群 按钮事件
        createGroupButton.setOnAction(event -> onBuildGroupAction());

        joinGroupButton.setOnAction(event -> {
            if (!ClientApplication.VIEW_MAP.containsKey(ViewMapConstant.ALL_GROUP_VIEW)) {
                new AllGroupView().createAllGroupView();
            }
        });

        // 设置 退群 按钮事件
        quitGroupButton.setOnAction(event -> {
            List<GroupItem> groupItems = this.groupItemListView.getSelectionModel().getSelectedItems();
            if (groupItems != null && groupItems.size() == 1) {
                Map<String, Object> map = new HashMap<>(2);
                map.put("choice", "signOutGroup");
                map.put("groupId", groupItems.get(0).getGroupId());
                ClientWriteHandler.sendRequest(map);
            }
        });

        // 放 建群 和 退群 两个按钮的Box
        HBox buttonsBox = new HBox();
        buttonsBox.getChildren().add(createGroupButton);
        buttonsBox.getChildren().add(joinGroupButton);
        buttonsBox.getChildren().add(quitGroupButton);

        HBox.setMargin(joinGroupButton, new Insets(0, 0, 0, 10));
        HBox.setMargin(quitGroupButton, new Insets(0, 0, 0, 168));

        // 设置群聊列表界面的布局
        groupListBox.getChildren().add(this.groupItemListView);
        groupListBox.getChildren().add(buttonsBox);


        // 设置总体布局
        groupListBox.setPadding(new Insets(10, 5, 20, 5));
        VBox.setMargin(buttonsBox, new Insets(20, 0, 0, 0));

        Scene scene = new Scene(groupListBox, 400, 400);
        this.stage.setTitle("群聊列表(双击进入群聊)");
        this.stage.setScene(scene);
        this.stage.show();

        // 当群聊列表关闭的时候, 把viewMap中的这个群聊列表删除
        this.stage.setOnCloseRequest(event -> ClientApplication.VIEW_MAP.remove(ViewMapConstant.GROUP_LIST_VIEW));

    }

    /**
     * 点击群事件, 如果是双击则打开群聊
     * @param event 事件
     */
    private void onOpenGroupAction(MouseEvent event) {
        if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
            ObservableList<GroupItem> groupData = this.groupItemListView.getItems();
            int index = this.groupItemListView.getSelectionModel().getSelectedIndex();
            GroupItem groupItem;
            try {
                groupItem = groupData.get(index);
            } catch (ArrayIndexOutOfBoundsException e) {
                return;
            }
            if (this.groupChatSet.contains(Integer.parseInt(groupItem.getGroupId()))) {
                this.logger.info("已存在的群聊...");
                return;
            }
            this.groupChatSet.add(Integer.parseInt(groupItem.getGroupId()));
            Group group = new Group();
            group.setGroupId(Integer.parseInt(groupItem.getGroupId()));
            group.setGroupName(groupItem.getGroupName());
            new GroupChatView(group).createGroupChatView();
        }
    }

    /**
     * 建群
     */
    private void onBuildGroupAction() {
        // 对话框内容
        VBox contentBox = new VBox();
        TextField groupName = new TextField();
        groupName.setPromptText("群名");        // 设置透明内容
        contentBox.getChildren().add(groupName);

        // Dialog -> DialogPane -> Root Node
        DialogPane dialogPane = new DialogPane();
        dialogPane.setContent(contentBox);

        // 添加按钮
        ButtonType ok = new ButtonType("确定创建", ButtonBar.ButtonData.OK_DONE);
        dialogPane.getButtonTypes().add(ok);

        // 创建对话框
        Dialog<ButtonType> dlg = new Dialog<>();
        dlg.setDialogPane(dialogPane);
        dlg.setTitle("填写群名");

        // 显示对话框, 并接收返回结果
        Optional<ButtonType> result =  dlg.showAndWait();
        if (result.isPresent() && result.get().getButtonData() == ButtonBar.ButtonData.OK_DONE) {
            String name = groupName.getText();  // 获取群名
            if (name == null || "".equals(name.trim())) {
                return;
            }
            name = name.trim();
            // 发送建群信息
            Map<String, Object> map = new HashMap<>(2);
            map.put("choice", "buildGroup");
            map.put("groupName", name);
            ClientWriteHandler.sendRequest(map);
        }
    }

}
